package com.ylr.blog.framework.service.impl;

import com.ylr.base.common.dto.PageDto;
import com.ylr.blog.common.dto.blog_tag.BlogTagDto;
import com.ylr.base.common.enums.CommonEnum;
import com.ylr.base.common.enums.ResultEnum;
import com.ylr.base.common.exception.YlrException;
import com.ylr.base.common.po.user.UserPo;
import com.ylr.base.common.tool.PageQuery;
import com.ylr.blog.common.vo.blog_tag.BlogTagFormVo;
import com.ylr.blog.common.vo.blog_tag.BlogTagVo;
import com.ylr.blog.framework.service.BlogTagService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylr.base.common.utils.UserUtils;
import com.ylr.base.framework.service.SnowflakeService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ylr.blog.framework.mapper.BlogTagMapper;
import com.ylr.blog.framework.entity.BlogTagEntity;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-05-23 22:24:25
 * className: BlogTagServiceImpl
 * version: 1.0
 * description:
 */
@Service("blogTagService")
@AllArgsConstructor
public class BlogTagServiceImpl extends ServiceImpl<BlogTagMapper, BlogTagEntity> implements BlogTagService {

    private static final Logger log = LoggerFactory.getLogger(BlogTagServiceImpl.class);

    private final SnowflakeService snowflakeService;

    @Override
    public void saveBlogTag(BlogTagVo blogTagVo) {
        // 获取正在保存博客标签的用户
        UserPo userPo = UserUtils.getUser();
        Date date = new Date();

        BlogTagEntity blogTag = this.getNewBlogTag(blogTagVo, userPo, date);
        // 保存博客标签
        baseMapper.insert(blogTag);
        log.info("博客标签保存完成");
    }

    @Override
    public PageDto<BlogTagDto> pageBlogTagList(BlogTagFormVo blogTagFormVo) {

        Page<BlogTagEntity> page = PageQuery.initPage(blogTagFormVo);

        LambdaQueryWrapper<BlogTagEntity> blogTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询字段
        blogTagLambdaQueryWrapper.select(BlogTagEntity::getId, BlogTagEntity::getName, BlogTagEntity::getSort,
                BlogTagEntity::getStatus, BlogTagEntity::getCreateTime);
        // 匹配条件
        blogTagLambdaQueryWrapper.like(StringUtils.isNotBlank(blogTagFormVo.getWord()), BlogTagEntity::getName, blogTagFormVo.getWord())
                .eq(Objects.nonNull(blogTagFormVo.getStatus()), BlogTagEntity::getStatus, blogTagFormVo.getStatus())
                .eq(BlogTagEntity::getDeleteStatus, CommonEnum.DELETE_NO.getValue());
        // 查询数据
        baseMapper.selectPage(page, blogTagLambdaQueryWrapper);

        List<BlogTagEntity> blogTagList = page.getRecords();
        long totalNum = page.getTotal();
        if (blogTagList.isEmpty()) {
            log.info("博客标签数据为空");
            return new PageDto<>();
        }
        // 数据转换
        List<BlogTagDto> blogTagDtoList = new ArrayList<>(blogTagList.size());
        for (BlogTagEntity blogTag : blogTagList) {
            BlogTagDto blogTagDto = this.getBlogTagDto(blogTag);
            blogTagDtoList.add(blogTagDto);
        }

        return new PageDto<>(blogTagDtoList, totalNum, blogTagFormVo.getPageNo(), blogTagFormVo.getPageSize());
    }

    @Override
    public BlogTagDto getBlogTag(Long id) {

        // 查询数据
        BlogTagEntity blogTag = baseMapper.selectById(id);

        return this.getBlogTagDto(blogTag);
    }

    @Override
    public Integer getNextSort() {
        Integer maxSort = baseMapper.selectMaxSort(CommonEnum.DELETE_NO.getValue());
        if (Objects.isNull(maxSort)) {
            maxSort = 0;
        }
        return maxSort + 1;
    }

    @Override
    public void updateBlogTag(BlogTagVo blogTagVo) {
        // 获取正在修改博客标签的用户
        UserPo userPo = UserUtils.getUser();
        Date date = new Date();

        BlogTagEntity blogTag = new BlogTagEntity();
        blogTag.setId(blogTagVo.getId())
                .setName(blogTagVo.getName())
                .setSort(blogTagVo.getSort())
                .setUpdateTime(date)
                .setUpdateUser(userPo.getUsername())
                .setUpdateUserId(userPo.getId());
        // 修改数据
        int count = baseMapper.updateById(blogTag);
        log.info("修改博客标签完成。count={}", count);
        if (count == 0) {
            throw new YlrException(ResultEnum.NOT_FOUND);
        }
    }

    @Override
    public void deleteBlogTag(List<Long> idList) {
        // 获取正在删除博客标签的用户
        UserPo userPo = UserUtils.getUser();
        Date date = new Date();

        LambdaUpdateWrapper<BlogTagEntity> blogTagLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        // 设置字段值
        blogTagLambdaUpdateWrapper.set(BlogTagEntity::getDeleteStatus, CommonEnum.DELETE_YES.getValue())
                .set(BlogTagEntity::getUpdateTime, date)
                .set(BlogTagEntity::getUpdateUser, userPo.getUsername())
                .set(BlogTagEntity::getUpdateUserId, userPo.getId());
        // 匹配条件
        blogTagLambdaUpdateWrapper.in(BlogTagEntity::getId, idList)
                .eq(BlogTagEntity::getDeleteStatus, CommonEnum.DELETE_NO.getValue());
        // 更新数据
        int count = baseMapper.update(null, blogTagLambdaUpdateWrapper);
        log.info("删除博客标签完成。count={}", count);
        if (count == 0) {
            throw new YlrException(ResultEnum.NOT_FOUND);
        }
    }

    /**
     * 博客标签参数转成博客标签实体对象
     * @param blogTagVo 博客标签参数对象
     * @return 博客标签实体对象
     */
    private BlogTagEntity getNewBlogTag(BlogTagVo blogTagVo, UserPo userPo, Date date) {
        BlogTagEntity blogTag = new BlogTagEntity();
        blogTag.setId(snowflakeService.getId())
                .setName(blogTagVo.getName())
                .setSort(blogTagVo.getSort())
                .setStatus(CommonEnum.STATUS_USE.getValue())
                .setDeleteStatus(CommonEnum.DELETE_NO.getValue())
                .setUpdateTime(date)
                .setUpdateUser(StringUtils.EMPTY)
                .setUpdateUserId(CommonEnum.DEFAULT_ID.getLongValue())
                .setCreateTime(date)
                .setCreateUser(userPo.getUsername())
                .setCreateUserId(userPo.getId());
        return blogTag;
    }

    /**
     * 博客标签实体对象封装
     * @param blogTag 博客标签实体对象
     * @return 封装结果
     */
    private BlogTagDto getBlogTagDto(BlogTagEntity blogTag) {
        BlogTagDto blogTagDto = new BlogTagDto();
        blogTagDto.setId(blogTag.getId().toString())
                .setName(blogTag.getName())
                .setSort(blogTag.getSort())
                .setStatus(blogTag.getStatus())
                .setCreateTime(blogTag.getCreateTime());
        return blogTagDto;
    }
}